<template>
  <div>
    <a-page-header class="pt-0" @back="back" :title="t('填写表单')"></a-page-header>
    <a-spin :spinning="table.loading" class="w-[100%]" v-if="userInfo">
      <a-form
        layout="vertical"
        @finish="submit"
        :rules="formRules"
        :model="userInfo.user"
        ref="formRef"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 8 }"
      >
        <a-card :bordered="false" :body-style="{ paddingTop: '0' }">
          <a-form-item :rules="{ required: true }" name="nickName" :label="t('昵称')">
            <a-input v-model:value="userInfo.user.nickName" />
          </a-form-item>

          <a-form-item :rules="{ required: true }" name="userName" :label="t('用户名')">
            <a-input v-model:value="userInfo.user.userName" />
          </a-form-item>

          <a-form-item name="telephone" :label="t('手机号')">
            <a-input :maxlength="11" class="w-[100%]" v-model:value="userInfo.user.telephone" />
          </a-form-item>

          <a-form-item name="password" :label="t('密码')" v-if="!userInfo.user.userId">
            <a-input-password v-model:value="userInfo.user.password" />
          </a-form-item>

          <a-form-item :label="t('角色')">
            <a-select
              allow-clear
              :field-names="{ label: 'roleName', value: 'roleId' }"
              :options="userInfo.roles"
              v-model:value="userInfo.roleIds"
              mode="multiple"
            ></a-select>
          </a-form-item>

          <div class="flex gap-4">
            <a-button type="primary" htmlType="submit">{{ t('保存') }}</a-button>
            <a-button @click="reset">{{ t('重置') }}</a-button>
          </div>
        </a-card>
      </a-form>
    </a-spin>
  </div>
</template>

<script setup lang="ts">
import type { IResponse } from '@/api/config/types';
import { list } from '../data/curd';
import { allowEditMenu, table } from '../data/data';
import { formRef, userInfo, formRules } from '../data/form';
import { addUser, updateUser } from '@/api/modules/user/user';
import { notify } from '@/utils/common/common';

const { t } = useI18n();
const back = () => {
  allowEditMenu.value = false;
  reset();
};
const submit = async () => {
  table.value.loading = true;
  try {
    let result: IResponse | undefined = undefined;
    userInfo.value.user.roleIds = userInfo.value.roleIds;
    if (!userInfo.value.user.userId) {
      const { data } = await addUser(userInfo.value.user);
      result = data;
    } else {
      const { data } = await updateUser(userInfo.value.user);
      result = data;
    }
    notify(result);
    await list();
    back();
  } catch (error) {
    table.value.loading = false;
  }
};
const reset = () => {
  formRef.value?.resetFields();
};
</script>

<style lang="scss" scoped></style>
